var that
class Tab {
    constructor(id){
        // 获取元素
        that = this;
        this.main = document.querySelector(id);
        this.add = this.main.querySelector('.add');
        this.ul = this.main.querySelector('.tabTop ul:first-child');
        this.tabConten = this.main.querySelector('.tabConten');
        this.init();
    }
    init(){
        this.updataNode();
        this.add.onclick = this.addTab;
        for(var i = 0; i < this.lis.length; i++){
            this.lis[i].index = i;
            this.lis[i].onclick = this.taggleTab;
            this.removes[i].onclick = this.delectTab;
            this.spans[i].ondblclick = this.editTab;
            this.sections[i].ondblclick = this.editTab;
        }
    }
    updataNode(){
        this.lis = this.main.querySelectorAll('li');
        this.sections = this.main.querySelectorAll('section');
        this.removes = this.main.querySelectorAll('.icon-guanbi');
        this.spans = this.main.querySelectorAll('.tabTop li span:first-child');
    }
    // 切换功能
    taggleTab(){
        that.clearClass();
        this.className = 'bdt';
        that.sections[this.index].className = 'active'
    }
    clearClass(){
        for (var i = 0 ; i < this.lis.length; i++){
            this.lis[i].className = '';
            this.sections[i].className = '';
        }
    }
    // 添加功能
    addTab(){
        that.clearClass();
        var random = Math.random();
        var li = '<li class="bdt"><span>新选项</span><span class="iconfont icon-guanbi"></li>';
        var section = '<section class="active">测试 ' + random+'</section>';
        that.ul.insertAdjacentHTML('beforeend',li);
        that.tabConten.insertAdjacentHTML('beforeend',section);
        that.init();
    }
    // 删除功能
    delectTab(e){
        e.stopPropagation();//阻止冒泡
        var index = this.parentNode.index;
        // console.log(index)
        that.lis[index].remove();
        that.sections[index].remove();
        that.init();
        // 删除选中状态的项，
        if(document.querySelector('.bdt')) return;
        index-- || index++;
        that.lis[index] && that.lis[index].click();
    }
    //编辑功能
    editTab(){
        var str = this.innerHTML;
        // 双击禁止选定文字
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        this.innerHTML = '<input type="text" />';
        var input = this.children[0];
        input.value = str;
        input.select();// 文本框内容处于选定状态
        // 当文本框失去光标的时候,把值给span
        input.onblur = function(){
            this.parentNode.innerHTML = this.value
        };
        // 当按下回车键的时候，把值给span
        input.onkeyup = function(e){
            if(e.keyCode === 13){
                // 手动调用表单失去焦点事件
                this.blur();
            }
        }
    }
}

new Tab('#tab')